#!/usr/bin/env python
# coding=utf8
# Last Change: 2010-07-16 09:57:44

from database import Account, Message, DelayedMessage
import gtalk

from google.appengine.ext import db
from google.appengine.api import xmpp

import time
import logging
from datetime import datetime, timedelta

def check_status():
  for a in Account.all():
    is_online = xmpp.get_presence(a.gtalk)
    is_login = is_online and not a.online
    is_status_changed = a.online != is_online
    # he changed the gtalk status
    if is_status_changed:
      a.online = is_online
      if not is_online:
        a.last_leave = datetime.now()
      db.put(a)
    # he is just login
    if is_login and a.last_leave:
      if (datetime.now() - a.last_leave) > timedelta(minutes=15):
        q = db.GqlQuery('SELECT * FROM AccessPoint WHERE user = :1', a.name)
        for ap in q:
          access_point = q.get()
          access_point.delete()
    if is_online:
      send_delayed_messages(a)

def send_delayed_messages(account):
  time = datetime(year=1970, month=1, day=1)
  message_dict = dict()
  participants_dict = dict()
  count = 0
  while True:
    q = db.GqlQuery('SELECT * FROM DelayedMessage WHERE user = :1 AND time > :2 ORDER BY time ASC', account.name, time)
    # all message processed
    if q.count(1) == 0:
      break
    # put delayed message to the dict according to the tag
    for dm in q:
      count += 1
      time = max(time, dm.time)
      message = dm.message
      tag = message.tag
      if tag in message_dict:
        message_list = message_dict[tag]
        participants = participants_dict[tag]
      else:
        message_list = list()
        participants = set()
      message_list.append(message)
      participants.add(message.sender)
      message_dict[tag] = message_list
      participants_dict[tag] = participants
      dm.delete()
  if count == 0:
    return
  # summary
  str = '\n'
  str += "** when you offline, there\'s %d messages is sent" % count
  gtalk.send_notify(str, account.gtalk)
  # for each tag, send the summary or whole conversation to him
  for tag, messages in message_dict.iteritems():
    participants = participants_dict[tag]
    messages.sort(cmp=lambda x, y : 1 if (x.time > y.time) else 0 if (x.time == y.time) else -1)
    # gtalk: --------------------
    str = '\n'
    # gtalk: tag: test 
    if tag:
      str += '** tag: %s\n' % tag
    # gtalk: participants: user1 user2
    str += '** participants:'
    for p in participants: 
      str += ' %s' % p
    # each message
    for m in messages:
      # format whole message but ignore the tag
      str += '\n' + '-' * 40
      str += gtalk.format_raw_message(m.sender, m.to, None, m.content, m.time)
    gtalk.send_notify(str, account.gtalk)

def main():
  fails = 0
  success = 0
  while success < 1:
    try:
      check_status()
      success += 1
    except:
      fails += 1
      if fails >= 5:
        raise

if __name__ == '__main__':
  main()
